﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;
using MyGeneration.dOOdads;

namespace WebUI
{
    public partial class Contract : BasePage
    {
        const string WHOLESALE = "";
        const string SALE = "";

        public bool IsSalePrice
        {
            get
            {
                if (ViewState["IsSalePrice"] == null)
                    ViewState["IsSalePrice"] = true;
                return (bool)ViewState["IsSalePrice"];
            }
            set { ViewState["IsSalePrice"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);
            if (!IsPostBack)
            {
                ClearAll();

                //Load for Combobox ACTK
                Customers cust = Customers.GetAllActiveCustomers();
                cust.Sort = Customers.ColumnNames.CustomerName + " asc";
                ddlCustomer.DataTextField = Customers.ColumnNames.CustomerName;
                ddlCustomer.DataValueField = Customers.ColumnNames.ID;
                ddlCustomer.DataSource = cust.DefaultView;
                ddlCustomer.DataBind();
                RefreshCustPrice();
            }
        }

        private void ClearAll()
        {
            Contracts contract = new Contracts();
            contract.LoadByPrimaryKey(-1);
            addContract.NewContracts = contract;
            addContract.Refresh();
            btnSubmit.Enabled = Branches.CurrentBranchID == SessionUser.BranchID;
        }

        public string GetAddServicePageLink()
        {
            return "EditPages/AddService.aspx?key=" + addContract.SourceObjectSessionID;
        }

        protected void btnRemoveContract_Click(object sender, EventArgs e)
        {
            addContract.DeleteCheckedItems();
            addContract.Refresh();
        }

        protected void btnAddService_Click(object sender, EventArgs e)
        {
            addContract.Refresh();
        }

        protected void btnAddIMEI_OnClick(object sender, EventArgs e)
        {
            try
            {
                addContract.AddIMEI(txtIMEI.Text);
                txtIMEI.Text = "";
                updateIMEI.Update();
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("focusIMEI();", 1), true);
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("Contract.aspx.cs", "btnAddIMEI_OnClick", ex.StackTrace);
                ShowErrorMessage(panelGrid, ex.Message);
            }
        }

        protected void btnNew_OnClick(object sender, EventArgs e)
        {
            ClearAll();
            btnSubmit.Visible = true;
        }

        protected void ddlCustomer_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            RefreshCustPrice();
        }

        private void RefreshCustPrice()
        {
            int custID;
            try
            {
                custID = int.Parse(ddlCustomer.SelectedValue);
            }
            catch (Exception ex)
            {
                custID = -1;
            }
            IsSalePrice = !View_Customers.GetPriceType(custID);
            lblCustPrice.Text = IsSalePrice ? SALE : WHOLESALE;
        }

        protected void ddlCustomer_OnItemInserted(object sender, EventArgs e)
        {
            string cust = ddlCustomer.Text;
            lblCustPrice.Text = SALE;
        }

        protected void btnSubmit_OnClick(object sender, EventArgs e)
        {
            TransactionMgr tx = TransactionMgr.ThreadTransactionMgr();
            try
            {
                tx.BeginTransaction();

                int custID = 0;

                try
                {
                    custID = int.Parse(ddlCustomer.SelectedValue);
                }
                catch(Exception ex1)
                {
                    custID = 0;
                }

                addContract.NewContracts.Rewind();
                for (int i = 0; i < addContract.NewContracts.RowCount; i++)
                {
                    if (addContract.NewContracts.IsColumnNull(Contracts.ColumnNames.NetworkID))
                    {
                        ShowErrorMessage(panelGrid, "(*) Please add service for contract #" + (i + 1).ToString());
                        tx.RollbackTransaction();
                        return;
                    }
                }

                Sequence seq = new Sequence();
                View_ProductDetails prodDetails;

                addContract.NewContracts.Rewind();
                for (int i = 0; i < addContract.NewContracts.RowCount; i++ )
                {
                    addContract.NewContracts.BranchID = Branches.CurrentBranchID;
                    addContract.NewContracts.Deleted = false;
                    addContract.NewContracts.LastModifiedByUser = SessionUser.ID;
                    addContract.NewContracts.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                    addContract.NewContracts.CreatedByUser = SessionUser.ID;
                    addContract.NewContracts.CreatedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                    addContract.NewContracts.ContractNo = seq.GetNewID("Contracts");

                    prodDetails = View_ProductDetails.GetProductDetailsByID(addContract.NewContracts.ProductDetailID);

                    Invoices invoice = new Invoices();
                    invoice.AddNew();
                    invoice.BranchID = Branches.CurrentBranchID;
                    invoice.Deleted = false;
                    invoice.InvoiceNo = seq.GetNewID("Invoices");
                    invoice.SaleUser = SessionUser.ID;
                    invoice.LastModifiedByUser = SessionUser.ID;
                    invoice.CreatedByUser = SessionUser.ID;
                    invoice.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                    invoice.CreatedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                    invoice.PaidAmount = 0;
                    if(custID > 0)
                        invoice.CustomerID = custID;
                    invoice.CustomerName = ddlCustomer.SelectedItem.Text;
                    invoice.InvoiceTypeID = SysVars.CashInvoiceType;
                    invoice.TotalAmount = addContract.NewContracts.MPP + addContract.NewContracts.Commission + addContract.NewContracts.Rebate;
                    invoice.GSTTotalAmount = prodDetails.GST ? Math.Round(invoice.TotalAmount * SysVars.GST / (SysVars.GST + 100), 2) : 0;
                    invoice.InvoiceCategory = (byte)Invoices.InvoiceCategories.Contract;
                    invoice.IsRetail = true;
                    invoice.Save();
                    addContract.NewContracts.InvoiceID = invoice.ID;

                    if (custID > 0)
                    {
                        invoice.CustomerID = custID;

                        POSSystem.BLL.Customers cust = new POSSystem.BLL.Customers();
                        cust.UpdateCustomerAmt(custID, invoice.TotalAmount, invoice.PaidAmount);
                    }

                    InvoiceDetails ivcDetails = new InvoiceDetails();
                    ivcDetails.AddNew();
                    ivcDetails.BranchID = Branches.CurrentBranchID;
                    String desc = prodDetails.ProductName + string.Format("<br/><span class='hintBold'>IMEI/Serial: {0} </span>", prodDetails.IMEI);
                    ivcDetails.AddInfo(invoice.ID, prodDetails.ProductID, prodDetails.IMEI, 1,
                        invoice.GSTTotalAmount, invoice.TotalAmount, 0, prodDetails.Cost, desc);
                    ivcDetails.LastModifiedByUser = SessionUser.ID;
                    ivcDetails.s_ItemType = ((byte)Invoices.InvoiceCategories.Contract).ToString();
                    ivcDetails.Save();

                    ProductDetails prod = new ProductDetails();
                    prod.LoadByPrimaryKey(prodDetails.ID);
                    if (prod.ProductStatusID == (int)ProductDetails.ProductStatus.Saled)
                    {
                        throw new Exception(string.Format("{0} is not available in stock!"));
                    }
                    prod.ProductStatusID = (int)ProductDetails.ProductStatus.Saled;
                    prod.Save();

                    ProductDetailHistories productHistory = new ProductDetailHistories();
                    productHistory.AddNew();
                    productHistory.BranchID = Branches.CurrentBranchID;
                    productHistory.AddInfo(prodDetails.ID, (int)ProductDetails.ProductStatus.Saled,
                        0,
                        String.Format("Saled to {1}. User: ''. Price: {0:C}", invoice.TotalAmount, invoice.CustomerName),
                        prodDetails.SupplierID, invoice.TotalAmount);
                    productHistory.UserID = SessionUser.ID;
                    productHistory.Save();

                    Products.SyncProductQty(prod.ProductID);

                    addContract.NewContracts.MoveNext();
                }

                addContract.NewContracts.Save();

                tx.CommitTransaction();
                btnSubmit.Visible = false;
                ShowHintMessage(panelGrid, "(*) All contract(s) have been submitted successfully! ");
            }
            catch (Exception ex)
            {
                tx.RollbackTransaction();
                ErrorLog.WriteToFile("Contract.aspx.cs", "btnSubmit_OnClick", ex.StackTrace);
                ShowErrorMessage(panelGrid, "(*) Error:" + ex.Message);
            }
        }
    }
}
